package cn.gcjxsc.filter;

import com.google.gson.Gson;
import com.zgxl.common.util.AjaxResponse;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author pumbaa
 * @since 1.0
 */
public class AuthUtil {

    /**
     * 登陆超时
     * @param response
     */
    public static void ajaxResponse(HttpServletResponse response){
        AjaxResponse model = AjaxResponse.ajaxFailure("登陆超时,请重新登陆后操作");

        response.setContentType("application/json;charset=utf-8");
        Gson gson = new Gson();
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            printWriter.write(gson.toJson(model));
            printWriter.flush();
            printWriter.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if (null != printWriter) {
                printWriter.close();
            }
        }
    }

    /**
     * 取得php session id
     * @param request
     * @return
     */
    public static String getPHPSessionId(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (null == cookies) {
            return null;
        }
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (name.equals("PHPSESSID")) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
